#include "paramterwidget.h"
#include "ui_paramterwidget.h"

ParamterWidget::ParamterWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ParamterWidget)
{
    ui->setupUi(this);
    db_init();
    init();
    db_load_all();
}

ParamterWidget::~ParamterWidget()
{
    db_update();
    delete ui;
}

void ParamterWidget::db_init()
{
    m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setDatabaseName("object.db");
    if (!m_db.open()) {
        qDebug() << "Database open failed:" << m_db.lastError().text();
    }

}

bool ParamterWidget::db_update()
{
    if (!m_db.isOpen()) {
        qDebug() << "Database is not open!";
        return false;
    }

    QSqlQuery query(m_db);
    QString baseSql = "INSERT OR REPLACE INTO setting (id, name, high_tm, low_tm, high_hm, low_hm, high_ill, low_ill) "
                      "VALUES (:id, :name, :high_tm, :low_tm, :high_hm, :low_hm, :high_ill, :low_ill)";

    for (int i = 1; i <= 7; ++i) {
        QString highTmCtrlName = QString("high_tm_%1").arg(i);
        QString lowTmCtrlName = QString("low_tm_%1").arg(i);
        QString highHmCtrlName = QString("high_hm_%1").arg(i);
        QString lowHmCtrlName = QString("low_hm_%1").arg(i);
        QString highIllCtrlName = QString("high_ill_%1").arg(i);
        QString lowIllCtrlName = QString("low_ill_%1").arg(i);

        // 安全获取控件指针（避免空指针）
        QLineEdit *highTmCtrl = findChild<QLineEdit*>(highTmCtrlName);
        QLineEdit *lowTmCtrl = findChild<QLineEdit*>(lowTmCtrlName);
        QLineEdit *highHmCtrl = findChild<QLineEdit*>(highHmCtrlName);
        QLineEdit *lowHmCtrl = findChild<QLineEdit*>(lowHmCtrlName);
        QLineEdit *highIllCtrl = findChild<QLineEdit*>(highIllCtrlName);
        QLineEdit *lowIllCtrl = findChild<QLineEdit*>(lowIllCtrlName);

        if (!highTmCtrl || !lowTmCtrl) {  // 简化空指针检查
            qDebug() << "控件未找到:" << highTmCtrlName;
            continue;  // 跳过当前循环
        }

        // 绑定参数（自动处理数据类型）
        query.prepare(baseSql);
        query.bindValue(":id", i);  // 绑定 id
        query.bindValue(":name", QString::number(i));  // 确保 name 与 id 一致
        query.bindValue(":high_tm", highTmCtrl->text().toFloat());
        query.bindValue(":low_tm", lowTmCtrl->text().toFloat());
        query.bindValue(":high_hm", highHmCtrl->text().toInt());
        query.bindValue(":low_hm", lowHmCtrl->text().toInt());
        query.bindValue(":high_ill", highIllCtrl->text().toInt());
        query.bindValue(":low_ill", lowIllCtrl->text().toInt());

        if (!query.exec()) {
            qDebug() << "Update failed for index"<< i << ":" << query.lastError().text();
            return false;
        } else {
            qDebug() << "Successfully updated index" << i;
        }
    }
    return true;
}
bool ParamterWidget::db_select() {
    if (!m_db.isOpen()) {
        qDebug() << "Database is not open!";
        return false;
    }

    QSqlQuery query(m_db);
    QString sql = "SELECT * FROM setting WHERE id = :id";
    query.prepare(sql);
    query.bindValue(":id", paramIndex);  // 使用参数绑定

    if (!query.exec()) {
        qDebug() << "Select failed:" << query.lastError().text();
        return false;
    }

    if (query.next()) {
        high_tm = query.value("high_tm").toFloat();
        ui->high_tm_1->setText(query.value("high_tm").toString());
        low_tm = query.value("low_tm").toFloat();
        ui->low_tm_1->setText(query.value("low_tm").toString());
        high_hm = query.value("high_hm").toInt();
        ui->high_hm_1->setText(query.value("high_hm").toString());
        low_hm = query.value("low_hm").toInt();
        ui->low_hm_1->setText(query.value("low_hm").toString());
        high_ill = query.value("high_ill").toInt();
        ui->high_ill_1->setText(query.value("high_ill").toString());
        low_ill = query.value("low_ill").toInt();
        ui->low_ill_1->setText(query.value("low_ill").toString());
        return true;
    } else {
        qDebug() << "No data found for id" << paramIndex;
        return false;
    }
}

bool ParamterWidget::db_load_all()
{
    if (!m_db.isOpen()) {
        qDebug() << "Database not open!";
        return false;
    }

    QSqlQuery query(m_db);
    if (!query.exec("SELECT * FROM setting")) {
        qDebug() << "Query failed:" << query.lastError().text();
        return false;
    }

    while (query.next()) {
        int id = query.value("id").toInt();

        // 动态构造控件名称
        QString prefix = QString::number(id);
        QLineEdit* highTmEdit = findChild<QLineEdit*>("high_tm_" + prefix);
        QLineEdit* lowTmEdit = findChild<QLineEdit*>("low_tm_" + prefix);
        QLineEdit* highHmEdit = findChild<QLineEdit*>("high_hm_" + prefix);
        QLineEdit* lowHmEdit = findChild<QLineEdit*>("low_hm_" + prefix);
        QLineEdit* highIllEdit = findChild<QLineEdit*>("high_ill_" + prefix);
        QLineEdit* lowIllEdit = findChild<QLineEdit*>("low_ill_" + prefix);

        if (highTmEdit && lowTmEdit) {
            highTmEdit->setText(QString::number(query.value("high_tm").toFloat()));
            lowTmEdit->setText(QString::number(query.value("low_tm").toFloat()));
            highHmEdit->setText(QString::number(query.value("high_hm").toFloat()));
            lowHmEdit->setText(QString::number(query.value("low_hm").toFloat()));
            highIllEdit->setText(QString::number(query.value("high_ill").toFloat()));
            lowIllEdit->setText(QString::number(query.value("low_ill").toFloat()));
        } else {
            qDebug() << "控件未找到 ID:" << id;
        }
    }
    return true;
}

void ParamterWidget::init()
{
    m_Timer.start(500);
    connect(&m_Timer, &QTimer::timeout, [=](){
        // 动态生成控件名称并获取指针
        QString highTmCtrlName = QString("high_tm_%1").arg(paramIndex);
        QString lowTmCtrlName = QString("low_tm_%1").arg(paramIndex);
        QString highHmCtrlName = QString("high_hm_%1").arg(paramIndex);
        QString lowHmCtrlName = QString("low_hm_%1").arg(paramIndex);
        QString highIllCtrlName = QString("high_ill_%1").arg(paramIndex);
        QString lowIllCtrlName = QString("low_ill_%1").arg(paramIndex);

        // 安全转换控件指针（避免空指针崩溃）
        QLineEdit *highTmCtrl = findChild<QLineEdit*>(highTmCtrlName);
        QLineEdit *lowTmCtrl = findChild<QLineEdit*>(lowTmCtrlName);
        QLineEdit *highHmCtrl = findChild<QLineEdit*>(highHmCtrlName);
        QLineEdit *lowHmCtrl = findChild<QLineEdit*>(lowHmCtrlName);
        QLineEdit *highIllCtrl = findChild<QLineEdit*>(highIllCtrlName);
        QLineEdit *lowIllCtrl = findChild<QLineEdit*>(lowIllCtrlName);

        if (highTmCtrl && lowTmCtrl) {
            high_tm = highTmCtrl->text().toFloat();
            low_tm = lowTmCtrl->text().toFloat();
            high_hm = highHmCtrl->text().toInt();
            low_hm = lowHmCtrl->text().toInt();
            high_ill = highIllCtrl->text().toInt();
            low_ill = lowIllCtrl->text().toInt();
        } else {
            qDebug() << "控件未找到:" << highTmCtrlName << lowTmCtrlName;
        }
    });

    QString picStyle = "border-image: url(:/new/prefix1/Resource/ParTop1.png);";
    QString name = "南瓜";
    ui->ParamertBtn1->setPicName(picStyle,name,1);
    ui->ParamertBtn1->setIndex(0);
    m_ParamterBtnMap.insert(name,ui->ParamertBtn1);
    ui->ParamertBtn1->setClickedStyle();
    ui->stackedWidgetParamter->setCurrentIndex(0);

    picStyle = "border-image: url(:/new/prefix1/Resource/ParTop2.png);";
    name = "土豆";
    ui->ParamertBtn2->setPicName(picStyle,name,2);
    ui->ParamertBtn2->setIndex(1);
    m_ParamterBtnMap.insert(name,ui->ParamertBtn2);

    picStyle = "border-image: url(:/new/prefix1/Resource/ParTop3.png);";
    name = "生菜";
    ui->ParamertBtn3->setPicName(picStyle,name,3);
    ui->ParamertBtn3->setIndex(2);
    m_ParamterBtnMap.insert(name,ui->ParamertBtn3);

    picStyle = "border-image: url(:/new/prefix1/Resource/ParTop4.png);";
    name = "番茄";
    ui->ParamertBtn4->setPicName(picStyle,name,4);
    ui->ParamertBtn4->setIndex(3);
    m_ParamterBtnMap.insert(name,ui->ParamertBtn4);

    picStyle = "border-image: url(:/new/prefix1/Resource/ParTop5.png);";
    name = "胡萝卜";
    ui->ParamertBtn5->setPicName(picStyle,name,5);
    ui->ParamertBtn5->setIndex(4);
    m_ParamterBtnMap.insert(name,ui->ParamertBtn5);

    picStyle = "border-image: url(:/new/prefix1/Resource/ParTop6.png);";
    name = "草莓";
    ui->ParamertBtn6->setPicName(picStyle,name,6);
    ui->ParamertBtn6->setIndex(5);
    m_ParamterBtnMap.insert(name,ui->ParamertBtn6);

    picStyle = "border-image: url(:/new/prefix1/Resource/ParTop7.png);";
    name = "黄瓜";
    ui->ParamertBtn7->setPicName(picStyle,name,7);
    ui->ParamertBtn7->setIndex(6);
    m_ParamterBtnMap.insert(name,ui->ParamertBtn7);

    QMap<QString,ParameterBtn*>::iterator item = m_ParamterBtnMap.begin();
    while (item != m_ParamterBtnMap.end()) {

        connect(item.value(),&ParameterBtn::sigClicked,[=](QString name,int index)
        {
            paramIndex = index;
            QMap<QString,ParameterBtn*>::Iterator itembtn = m_ParamterBtnMap.begin();
            while (itembtn != m_ParamterBtnMap.end()) {
                if(itembtn.key() != name)
                {
                    ((ParameterBtn*)(itembtn.value()))->setNormalStyle();
                }
                itembtn++;
            }
            ui->stackedWidgetParamter->setCurrentIndex(m_ParamterBtnMap.value(name)->getIndex());
        });
        item++;
    }
}
